package hotgammon.domain;

public class BetamonMove implements MoveStrategy {
	
	public boolean move(Board board, Game game, Location from, Location to) {
		Color colorFrom = game.getColor(from);
		Color colorTo = game.getColor(to);
		Color colorCurrent = game.getPlayerInTurn();
		
		Location bar = Location.B_BAR;
		if(colorCurrent == Color.RED)
			bar = Location.R_BAR;
		
		Location opBar = Location.B_BAR;
		if(colorCurrent == Color.BLACK)
			opBar = Location.R_BAR;
		
		if(colorFrom == Color.NONE)
			return false;
		
		if(colorCurrent == Color.NONE)
			return false;
		
		if(game.getNumberOfMovesLeft() == 0)
			return false;
		
		if(to == bar)
			return false;
		
		if(game.getCount(bar) > 0 && colorCurrent == Color.BLACK) {
			if(from != bar || to.getIndex() < 1 || to.getIndex() > 6)
				return false;
		}
		
		if(game.getCount(bar) > 0 && colorCurrent == Color.RED) {
			if(from != bar || to.getIndex() < 19 || to.getIndex() > 24)
				return false;
		}
		
		if(colorTo != Color.NONE && colorFrom != colorTo && game.getCount(to) > 1)
			return false;
		
		if(colorCurrent == Color.BLACK && Location.distance(from, to) < 0)
			return false;
		
		if(colorCurrent == Color.RED && Location.distance(from, to) > 0)
			return false;
		
		if(!valueLeft(Math.abs(Location.distance(from, to)), game.diceValuesLeft()))
			return false;
		
		if(colorTo != Color.NONE && colorFrom != colorTo && game.getCount(to) == 1)
			board.move(to, opBar);
				
		return true;
	}
	
	/**
	private boolean isBlocked(Location bar, int dice, Location from, Location to) {
		Location[] locations = Location.values();
		if(bar == Location.B_BAR) {
			for(Location loc : locations) {
				if(loc.getIndex() >= Location.R1.getIndex() && loc.getIndex() <= Location.R6.getIndex() && Math.abs(Location.distance(from, to)) == dice)
					return true;
			}
		}
		else {
			for(Location loc : locations) {
				if(loc.getIndex() >= Location.B1.getIndex() && loc.getIndex() <= Location.B6.getIndex() && Math.abs(Location.distance(from, to)) == dice)
					return true;
			}
		}
			
		return false;
	}
	*/
	
	private boolean valueLeft(int dist, int[] left) {
		for(int isLeft : left)
			if(isLeft == dist)
				return true;
		
		return false;
	}
}
